const net = require('net');
const fs = require('fs');
const logFile = '/opt/test/info.log';
const moment =require('moment')
const errorFile = '/opt/test/error.log';
test();
const server = net.createServer((socket) => {
  console.log('客户端已连接');
 // socket.setEncoding('binary');
  socket.on('data', (data) => {
    try{
      const buff=Buffer.from(data,'utf8')
      log('buffer to hex：' + buff.toString('hex'));
      log('buffer to ascii：' + buff.toString('ascii'));
      log('buffer to binary：' + buff.toString('binary'));
      log('buffer：' + buff.toString());
    }catch (e) {
      log(e);
    }
  });

  socket.on('end', () => {
    log('客户端已断开连接');
  });
});

server.listen(9923, () => {
  log('服务器正在监听9923端口');
});

function log(info) {
  const time = moment().format('YYYY-MM-DD HH:mm:ss')
  console.log(time + ' ' + info);
  fs.appendFile(logFile, time + '-->' + info + '\r\n', 'utf8', err => {
  });
}

function test() {
  const buff=Buffer.from('hi word','utf8')
  log('buffer to hex：' + buff.toString('hex'));
  log('buffer to ascii：' + buff.toString('ascii'));
  log('buffer to binary：' + buff.toString('binary'));
}